#!/usr/bin/env bash

set -e

function log()
{
    echo "[$(date "+%Y-%m-%d %H:%M:%S")] $*"
}

function die()
{
    local _retValue="${1:-1}"
    local _msg="${2:-未知原因}"

    log "已退出：${_msg}"
    exit "${_retValue}"
}

if [ ! -f "${PWD}/autoMake" ]; then
    die 114 "请在项目根目录下运行！并使用./autoMake运行。"
fi

readonly DEBUG="${DEBUG:-false}"
readonly SINGLEFILE="${SINGLEFILE:-true}"

BUILDTYPE="Unknown"

if [ "${DEBUG}" == "true" ]; then
    BUILDTYPE="Debug"
else
    BUILDTYPE="Release"
fi

readonly BUILDTYPE

if [ $# -ge 2 ]; then
    Ver=$2
else
    Ver=1.0.0
fi

readonly ROOTDIR="${PWD}"
readonly BINDIR="${ROOTDIR}/WonderLab/bin/${BUILDTYPE}/net6.0"

function build()
{
   log "开始编译"
   cd "${ROOTDIR}" || die 2 "无法变更目录到 ${ROOTDIR}"

   dotnet build -c "${BUILDTYPE}"
   dotnet deb install
   dotnet rpm install
   log "编译结束" 
}

function package()
{
    log "开始打包"

    cd "${ROOTDIR}" || die 2 "无法变更目录到 ${ROOTDIR}"

    # 初始化输出目录
    local _finalDir="${ROOTDIR}/bin"
    rm -rf "${_finalDir}"
    mkdir -vp "${_finalDir}"

    local _targetRuntime="linux-x64"
    dotnet publish WonderLab -c Release -r "${_targetRuntime}" \
        --self-contained true \
        -p:PublishSingleFile="${SINGLEFILE}" \
        -p:PublishReadyToRun=true \
        -t:CreateDeb -t:CreateRpm

    local _publishDir="${BINDIR}/${_targetRuntime}/publish"

    # 移动deb和rpm包到输出目录中
    local _archiveName="${BINDIR}/${_targetRuntime}/WonderLab.$Ver.${_targetRuntime}"
    mv "${_archiveName}.deb" "${_finalDir}/linux-x86_64.deb"
    mv "${_archiveName}.rpm" "${_finalDir}/linux-x86_64.rpm"

    cd "${_publishDir}" || die 2 "无法变更目录到 ${_publishDir}"
    tar -zcvf "${_finalDir}/linux-x86_64.tar.gz" ./*
    log "打包完成！在bin目录下！"
    exit 0
}

if [ "$1" == "build" ]; then
    build
elif [ "$1" == "package" ]; then
    package
else
    log "帮助："
    log "build 只编译软件"
    log "package 打包软件"
    exit 1919
fi
